import { asyncRouterMap, constantRouterMap } from '@/router'
import { string } from 'jszip/lib/support'

/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role))
    } else {
        return true
    }
}

function hasModulePermission(modules, route) {
    modules = modules || []
    if (route.meta && route.meta.guid) {
        if (route.meta.guid == '2ddc00bf-2dd8-11ef-b3f9-00163e0d1539') {
            alert(modules.some(guid => route.meta.guid == guid))
        }
        return modules.some(guid => route.meta.guid == guid)
    } else {
        return true
    }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(routes, roles, modules) {
    // alert(JSON.stringify(modules))
    const res = []
    routes.forEach(route => {
        const tmp = {...route }
        if (hasPermission(roles, tmp) || hasModulePermission(modules, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRouter(tmp.children, roles, modules)
            }
            res.push(tmp)
        }
    })

    return res
}

const permission = {
    state: {
        routers: constantRouterMap,
        addRouters: []
    },
    mutations: {
        SET_ROUTERS: (state, routers) => {
            state.addRouters = routers
            state.routers = constantRouterMap.concat(routers)
        }
    },
    actions: {
        GenerateRoutes({ commit }, data) {
            // alert('左边整理导航栏')
            return new Promise(resolve => {
                const { roles, modules } = data
                let accessedRouters
                if (roles.includes('admin')) {
                    accessedRouters = asyncRouterMap
                } else {
                    accessedRouters = filterAsyncRouter(asyncRouterMap, roles, modules)
                }
                commit('SET_ROUTERS', accessedRouters)
                resolve()
            })
        }
    }
}

export default permission